﻿
$(function () {
	renderPage();

	// 添加 验证逻辑;
	var formValidate = $("#mainform").validate({
			rules : {
				user : "required",
				password : {
					required : true,
					minlength : 8
				},
				password_confirmation : {
					required : true,
					equalTo : "#password"
				},
				company : "required",
				legal : "required",
				legal_gender : "required",
				identification_number : "required",
				contact_person : "required",
				province : "required",
				city : "required",
				country : "required",
				address : "required",
				email : {
					required : true,
					email : true
				},
				main_category : "required",
				main_brand : "required",
				signflag : "required",
				captcha : "required",
				contact_phone:{
					required:true,
 					digits:true
				}
			},
			messages : {
				password_confirmation : {
					equalTo : "请输入相同密码"
				},
				signflag : "请接受协议！"
			},
			errorPlacement : function (error, element) {
				if (element.attr("name") == "signflag") {
					element.parents(".electronic-bottom").append(error);
				} else {
					element.parents(".input-info").after($("<div class='key-lbl' style='width:auto;'/>").append(error));
				}
			},
			ignore : ""

		});

	// 密码强度
	$("#password").on("keyup change", function () {

		var comm = /.{7,}/
		var leve_1 = /[a-z]{1,}/;
		var leve_2 = /[A-Z]{1,}/;
		var leve_3 = /[0-9]{1,}/;
		var leve_4 = /\W{1,}/; // 非单词字符。

		var pw = $(this).val();

		var pwLevel = -1;
		if (leve_1.test(pw) && leve_2.test(pw) && leve_3.test(pw) && comm.test(pw)) {
			// 强
			pwLevel = 2;
		} else if ((leve_1.test(pw) || leve_2.test(pw)) && leve_3.test(pw) && comm.test(pw)) {
			// 中
			pwLevel = 1;
		} else if (leve_1.test(pw) || leve_2.test(pw) || leve_3.test(pw) || leve_4.test(pw)) {
			// 弱
			pwLevel = 0;
		}

		if (-1 == pwLevel) {
			$("#pw-level").children().removeClass("pw-strength-chk");
		} else {
			var curitem = $("#pw-level").children().eq(pwLevel);
			curitem.addClass("pw-strength-chk").prevAll().addClass("pw-strength-chk");
			curitem.nextAll().removeClass("pw-strength-chk");
		}
	});

	// 提交申请
	$("#form-submit-btn").on("click", function () {
		$("#mainform").submit();
	});

	// 选择主营类别
	$("#category-btn").on("click", function () {
		if (typeof PAGE_DATA.modalCategoryData == 'undefined') {
			$.ajax({
				url : PAGE_CONFIG.requestUrl.categoryUrl, 
				type : 'get',
				dataType : 'json',
				success : function (result) {
					PAGE_DATA.modalCategoryData = $.extend([], result.data);
					CreateModalCateg(PAGE_DATA.modalCategoryData).showModal();
				},
				error : function (xhr, status, error) {
					CreateModalCateg([]).showModal();
				}
			});

		} else {
			CreateModalCateg(PAGE_DATA.modalCategoryData).showModal();
		}

	});

	// 选择主营品牌;
	$("#brand-btn").on("click", function () {
		if (typeof PAGE_DATA.modalBrandData == 'undefined') {
			$.ajax({
				url : PAGE_CONFIG.requestUrl.brandUrl,
				type : 'get',
				dataType : 'json',
				success : function (result) {
					PAGE_DATA.modalBrandData = $.extend([], result.data);
					CreateModalBrand(PAGE_DATA.modalBrandData).showModal();
				},
				error : function (xhr, status, error) {
					CreateModalBrand([]).showModal();
				}
			});
		} else {
			CreateModalBrand(PAGE_DATA.modalBrandData).showModal();
		}
	});

	// 注册类别;
	$("#regist-role").find("span").on("click", function () {
		var rolVal = $(this).attr("role");
		$(this).addClass("current").siblings().removeClass("current");

		// 供应商-0, 采购商-1, visibility, hidden, visible
		var roleFlg = (rolVal == "1");
		$("#regist-elec-docs").find(".sel-doc-more").css("visibility", roleFlg ? "hidden" : "visible");
		$("#agreement-file").css("display", roleFlg ? "none" : "");
		$("#mainform").attr("action", roleFlg ? PAGE_DATA.actionUrlB : PAGE_DATA.actionUrlS);
		
	});

	// 选择文件
	$("#regist-elec-docs").on("click", ".image-list", function () {
		var fileObj = $(this).find("[type='file']");
		fileObj[0].click();
	});
	
	// 零时预览图片,
	$("#regist-elec-docs").find("[type='file']").each(function(){
		$(this).AjaxFileUpload({
			action : PAGE_CONFIG.requestUrl.uploadimg,
			name : PAGE_CONFIG.requestUrl.preViewImg,
			onComplete : function(filename, response){
				$(this).parent().find("img").attr("src", response.data);
			}
		});		
	});

});

/*
 *  主营类别
 */
function CreateModalCateg(data) {

	// item-template
	var tmplObj = _.template($('#item-template').html());
	var tmplObjHtml = tmplObj(data);

	// 模态框, 选择主营类别 category-btn，
	var dial = dialog({
			id : "dialog-categ",
			width : 550,
			height : 400,
			title : "选择类别",
			content : tmplObjHtml,
			onshow : function () {
				// bind event
				var that = this;

				// bind event
				var dialogObj = $("[id='content:dialog-categ']");
				dialogObj.find(".info-item").on("click", function () {
					var id = $(this).attr("id");
					var start = id.lastIndexOf("-");
					var idx = id.substr(start + 1);
					$(this).addClass("hover").siblings().removeClass("hover");
					$("#info-detail-box-" + idx).show().siblings().hide();
				});

				// dialogObj.find(":checkbox");
				var codeStr = $("#main_category").val();
				var codeAry = codeStr.split(",");
				var codeStr = $("#main_category").val();

				_.each(codeAry, function (item) {
					dialogObj.find(":checkbox").filter("[code='" + item + "']").attr("checked", true);
				});

				//保存
				$("#modal-save-btn").on("click", function () {
					var codeAry = [];
					var txtAry = [];
					dialogObj.find(":checked").each(function () {
						codeAry.push($(this).attr("code"));
						txtAry.push($(this).attr("txt"));
					});
					$("#main_category").val(codeAry.join(","));

					addSelItems("sel-categ-box", txtAry);

					that.remove();
				});

				// 初始化 显示设定;
				$("#info-item-title-0").addClass("hover");
				$("#info-detail-box-0").show();
			}
		});

	return dial;
};

/*
 * 主营品牌
 */
function CreateModalBrand(data) {
	// item-template
	var tmplObj = _.template($('#item-template').html());
	var tmplObjHtml = tmplObj(data);

	// 模态框, 选择主营类别
	var dial = dialog({
			id : "dialog-brand",
			width : 550,
			height : 400,
			title : "选择品牌",
			content : tmplObjHtml,
			onshow : function () {

				var that = this;
				// bind event
				var dialogObj = $("[id='content:dialog-brand']");
				dialogObj.find(".info-item").on("click", function () {
					var id = $(this).attr("id");
					var start = id.lastIndexOf("-");
					var idx = id.substr(start + 1);
					$(this).addClass("hover").siblings().removeClass("hover");
					$("#info-detail-box-" + idx).show().siblings().hide();
				});

				// 渲染已选择项
				var codeStr = $("#main_brand").val();
				var codeAry = codeStr.split(",");
				_.each(codeAry, function (item) {
					dialogObj.find(":checkbox").filter("[code='" + item + "']").attr("checked", true);
				});

				//保存
				$("#modal-save-btn").on("click", function () {
					var codeAry = [];
					var txtAry = [];
					dialogObj.find(":checked").each(function () {
						codeAry.push($(this).attr("code"));
						txtAry.push($(this).attr("txt"));
					});
					$("#main_brand").val(codeAry.join(","));

					addSelItems("sel-brand-box", txtAry);

					that.remove();
				});

				// 初始化 显示设定;
				$("#info-item-title-0").addClass("hover");
				$("#info-detail-box-0").show();
			}

		});

	return dial;
};

function addSelItems(containerId, data) {
	var tmplObj = _.template($('#sel-item-templ').html());
	var tmplObjHtml = tmplObj(data);
	$("#" + containerId).html(tmplObjHtml);
};

// 渲染地址,
var addrTemplObj = _.template($('#addr-option-templ').html());

/*
渲染页面
 */
function renderPage() {

	commTemplUtil.initPage();

	$("#web-logo").attr("src", PAGE_DATA.logo);
	$("#mainform").attr("action", PAGE_DATA.actionUrlS);
	$("#user-agreement").attr("href", PAGE_DATA.userAgreementUrl);
	$("#supply-agreement").attr("href", PAGE_DATA.supplyAgreementUrl);

	// 省
	$.ajax({
		url : PAGE_CONFIG.requestUrl.addrProvince,
		type : 'get',
		dataType : 'json',
		success : function (result) {
			var datas = $.extend([], result.data);
			var tmplObjHtml = addrTemplObj(datas);
			$("#province").html(tmplObjHtml);
		},
		error : function (xhr, status, error) {
			var tmplObjHtml = addrTemplObj([]);
			$("#province").html(tmplObjHtml);
		}
	});

	$("#province").on("change", function () {
		var code = $(this).val();
		renderAddrCity(code);
	});

};

function renderAddrCity(provinceCode) {

	// 市
	$.ajax({
		url : PAGE_CONFIG.requestUrl.addrCity,
		type : 'post',
		dataType : 'json',
		data : {
			code : provinceCode,
			_token : COMM_DATA.csrfToken
		},
		success : function (result) {
			var datas = $.extend([], result.data);
			var tmplObjHtml = addrTemplObj(datas);
			$("#city").html(tmplObjHtml);
			$("#city").on("change", function () {
				var code = $(this).val();
				renderAddrCounty(code);
			});
		},
		error : function (xhr, status, error) {
			var tmplObjHtml = addrTemplObj([]);
			$("#city").html(tmplObjHtml);
		}
	});
	
	$("#city").empty().html(addrTemplObj([]));
	$("#country").empty().html(addrTemplObj([]));
};

function renderAddrCounty(cityCode) {
	// 区/县
	$.ajax({
		url : PAGE_CONFIG.requestUrl.addrCounty,
		type : 'post',
		dataType : 'json',
		data : {
			code : cityCode,
			_token : COMM_DATA.csrfToken
		},
		success : function (result) {
			var datas = $.extend([], result.data);
			var tmplObjHtml = addrTemplObj(datas);
			$("#country").html(tmplObjHtml);

			$("#country").on("change", function () {
				var code = $(this).val();
			});
		},
		error : function (xhr, status, error) {
			var tmplObjHtml = addrTemplObj([]);
			$("#country").html(tmplObjHtml);
		}
	});
};